/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amse.grigory.dchess.view;

import java.awt.Color;
import javax.swing.*;
import org.amse.grigory.dchess.kernel.*;
import org.amse.grigory.dchess.rules.*;

/**
 *
 * @author grigory
 */
public class DChessLabel extends JLabel implements IModelListener {

    private static final String CLOCK_ICON = "data/img/icons/clock.png";
    private IModel myModel;
    private int myColor;
    private static Icon ourClock = new ImageIcon(CLOCK_ICON);
    private String myName = "Player";

    public DChessLabel(IModel model, int color) {
        myModel = model;
        myColor = color;
        setHorizontalTextPosition(LEFT);
    }

    public void update() {
        int win = myModel.isWin();
        if (win != Rules.NOBODY_WIN) {
            setForeground(Color.BLUE);
            if (win == Rules.BLACK_WIN) {
                if (myColor == Rules.COLOR_BLACK) {
                    setText(myName + " has won!");
                } else {
                    setText(myName + " has lost!");
                }
            }
            if (win == Rules.WHITE_WIN) {
                if (myColor == Rules.COLOR_WHITE) {
                    setText(myName + " has won!");
                } else {
                    setText(myName + " has lost!");
                }
            }
            if (win == Rules.DRAW) {
                setText("Draw");
            }
            setIcon(null);
            repaint();
            return;
        }
        int time;
        if (myColor == Rules.COLOR_WHITE) {
            time = myModel.getWhiteTime();
            setText(myName + ":" + convertTime(time));
        } else {
            time = myModel.getBlackTime();
            setText(myName + ":" + convertTime(time));
        }
        if (myModel.getColor() == myColor) {
            if (!myModel.getLastMove().equals("")) {
                setText(getText() + "(" + myModel.getLastMove() + ")");
            }
            setForeground(Color.RED);
            setIcon(ourClock);
        } else {
            setForeground(Color.BLACK);
            setIcon(null);
        }
        repaint();
    }

    private String convertTime(int time) {
        if (time > 24 * 60 * 60) {
            return "";
        }
        int t = time;
        String ans = " " + (t % 60) + "sec.";
        t = t / 60;
        if (t == 0) {
            return ans;
        }
        ans = " " + (t % 60) + "min." + ans;
        t = t / 60;
        if (t == 0) {
            return ans;
        }
        ans = " " + (t % 60) + "hr." + ans;
        return ans;
    }

    public String getLabelName() {
        return myName;
    }

    public void setLabelName(String name) {
        myName = name;
    }
}
